<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-row>
          <el-form-item label="盘点日期" prop="checkYearMonth">
            <el-date-picker v-model="queryParams.checkYearMonth" clearable placeholder="请选择盘点日期" type="date">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="序号" prop="itemNo">
            <el-input v-model="queryParams.itemNo" clearable placeholder="请输入序号" @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="药品类别" prop="drugClass">
            <el-input v-model="queryParams.drugClass" clearable placeholder="请输入药品类别"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="药品编码" prop="drugCode">
            <el-input v-model="queryParams.drugCode" clearable placeholder="请输入药品编码"
                      @keyup.enter="handleQuery"/>
          </el-form-item>

          <el-form-item label="药品名称" prop="drugInfoId">
            <el-input v-model="queryParams.drugInfoId" clearable placeholder="请输入药品名称"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="库存单位" prop="storageId">
            <el-input v-model="queryParams.storageId" clearable placeholder="请输入库存单位"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain round type="primary" @click="generateInventory">
              <template
                #icon>
                <i-ep-plus/>
              </template>
              拉取盘点单
            </el-button>
            <el-button v-if="!saveTypeInfo" round type="warning" @click="solidFill">
              <template #icon>
                <i-ep-switch/>
              </template>
              实盘填充
            </el-button>
            <el-button v-if="!saveTypeInfo" plain round type="success" @click="temporarySave">
              <svg-icon class="mr5" icon-class="save"/>
              暂存(本页)
            </el-button>
            <el-button v-if="!saveTypeInfo" round type="success" @click="save">
              <svg-icon class="mr5" icon-class="save"/>
              保存盘点数据
            </el-button>
            <el-button v-if="!saveTypeInfo" round type="danger" @click="deleteInventory">
              <template #icon>
                <i-ep-delete/>
              </template>
              删除预盘点单
            </el-button>
            <el-button round type="primary" @click="extractInventory">
              <svg-icon class="mr5" icon-class="extract"/>
              提取盘点单
            </el-button>
            <el-form-item label="">
              <el-checkbox v-model="isZeroInventory" class="ml10"><span
                class="el-form-item__label">隐藏零库存</span>
              </el-checkbox>
            </el-form-item>
            <el-button plain round type="danger" @click="exportInventory">
              <svg-icon class="mr5" icon-class="export"/>
              导出
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div style="text-align: center;margin-bottom: 2px">
      <span v-if="drugInventoryCheckPreparationList.length >0" style="color: #0b9aff"> <span>盘点号：{{
          drugInventoryCheckPreparationList[0].inventoryNo
        }} | 盘点日期： {{
          $parseTime(drugInventoryCheckPreparationList[0].checkYearMonth, '{y}-{m}-{d}')
        }} | 盘点药房：{{ drugInventoryCheckPreparationList[0].storageName }}</span></span>
    </div>
    <el-table v-adaptive="55" :border="true" :cell-style="tableCellStyle" :data="drugInventoryCheckPreparationList"
              :header-cell-style="$headerCellStyle" :row-class-name="tableRowClassName" :stripe="true"
              highlight-current-row>
      <el-table-column :align="'center'" label="序号" prop="itemNo" width="60"/>
      <el-table-column :align="'center'" label="货柜" prop="location" width="70"/>
      <el-table-column :align="'left'" header-align="center" label="名称" prop="drugName" width="180">
        <template #default="scope">
          <span class="fz14 fw-bold">{{ scope.row.drugName }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" header-align="left" label="批号" prop="batchNo" width="120">
        <template #default="scope">
          <span class="ys-css">{{ scope.row.batchNo }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="药品类别" prop="drugClass" width="80">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['drug_classification']" :value="scope.row.drugClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" header-align="center" label="包装规格"
                       prop="packageSpec"
                       width="130"/>
      <el-table-column :align="'center'" label="包装单位" prop="packageUnitName" width="70"/>
      <el-table-column :align="'center'" label="进货单价(元)" prop="tradePrice"/>
      <el-table-column :align="'center'" label="零售单价(元)" prop="retailPrice"/>
      <el-table-column :align="'center'" label="帐面数量" prop="accountQuantity" width="140">
        <template #default="scope">
          <template v-if="scope.row.quantityMin > 0">
            <!--小包装-->
            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                           style="float: right"/>
            <div style="float: right;margin-right: 5px;font-weight: bold;">
              {{ scope.row.quantityMin }}
            </div>
          </template>
          <!--大包装-->
          <template v-if="scope.row.quantityMax > 0">
            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                           style="float: right"/>
            <div style="float: right;margin-right: 5px;font-weight: bold;">{{ scope.row.quantityMax }}
            </div>
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="实盘数量" prop="actualQuantity" width="210">
        <template #default="scope">
          <!--小包装-->
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                         style="float: right"/>
          <div style="float: right;margin-right: 5px;font-weight: bold;">
            <el-input v-model="scope.row.quantityMinActual" :disabled="saveTypeInfo" class="input-mr"
                      clearable style="width: 50px;" @blur="quantityActualBlur(scope.row, scope.$index, 'min')"
            ></el-input>
          </div>
          <!--大包装-->
          <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                         style="float: right"/>
          <div style="float: right;margin-right: 5px;font-weight: bold;">
            <el-input v-model="scope.row.quantityMaxActual" :disabled="saveTypeInfo" class="input-mr"
                      clearable style="width: 70px;" @blur="quantityActualBlur(scope.row, scope.$index, 'min')"
            ></el-input>
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="盈亏数" prop="profitQuantity" width="130">
        <template #default="scope">
          <template v-if="scope.row.profitQuantityMin != null && scope.row.profitQuantityMin != 0">
            <!--小包装-->
            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.minUnits"
                           style="float: right"/>
            <div style="float: right;margin-right: 5px;font-weight: bold;">
              {{ scope.row.profitQuantityMin }}
            </div>
          </template>
          <!--大包装-->
          <template v-if="scope.row.profitQuantityMax != null && scope.row.profitQuantityMax != 0">
            <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packageUnits"
                           style="float: right"/>
            <div style="float: right;margin-right: 5px;font-weight: bold;">{{ scope.row.profitQuantityMax }}
            </div>
          </template>
          <template v-if="(scope.row.profitQuantityMax == null && scope.row.profitQuantityMin == null) ||
                        (scope.row.profitQuantityMax == 0 && scope.row.profitQuantityMin == 0)">
            0
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="账面额" prop="accountMoney">
        <el-table-column :align="'right'" header-align="center" label="进价(元)" prop="accountMoney" width="90"/>
        <el-table-column :align="'right'" header-align="center" label="售价(元)" prop="accountMoneySales" width="90"/>
      </el-table-column>
      <el-table-column :align="'center'" label="实盘额" prop="">
        <el-table-column :align="'right'" header-align="center" label="进价(元)" prop="actualMoney" width="90"/>
        <el-table-column :align="'right'" header-align="center" label="售价(元)" prop="actualMoneySales" width="90"/>
      </el-table-column>
      <el-table-column :align="'center'" label="盈亏额" prop="">
        <el-table-column :align="'right'" header-align="center" label="进价(元)" prop="profitMoney" width="90"/>
        <el-table-column :align="'right'" header-align="center" label="售价(元)" prop="profitMoneySales" width="90"/>
      </el-table-column>
      <el-table-column :align="'center'" label="有效期" prop="expireDate" width="80">
        <template #default="scope">
          <span>{{ $parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="状态" prop="type" width="70px">
        <template #default="scope">
          {{
            scope.row.saveType === '0' ? '新生成' : scope.row.saveType === '1' ? '已保存' : scope.row.saveType === '2' ? '实盘填充' : '暂存'
          }}
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="totalPreparation > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                :pageSizes="[pageSize, 1000]" :total="totalPreparation" @pagination="paginationClick"/>
    <el-dialog v-model="open" :close-on-click-modal="false" :title="title" append-to-body class="dialog-mb"
               width="45%">
      <el-table :border="true" :data="groupInventoryList" :stripe="true" height="400" highlight-current-row
                :header-cell-style="$headerCellStyle">
        <el-table-column :align="'center'" label="盘点日期" prop="checkYearMonth">
          <template #default="scope">
            <span>{{ $parseTime(scope.row.checkYearMonth, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="盘点号" prop="inventoryNo"/>
        <el-table-column :align="'center'" label="保存标志" prop="saveType" width="90px">
          <template #default="scope">
            {{
              scope.row.saveType === '0' ? '新生成' : scope.row.saveType === '1' ? '已保存' : scope.row.saveType === '2' ? '实盘填充' : '暂存'
            }}
          </template>
        </el-table-column>
        <el-table-column :align="'center'" label="库存是否调整" prop="status" width="90px">
          <template #default="scope">
            <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column align="left" class-name="small-padding fixed-width" fixed="right" header-align="center"
                         label="操作"
                         width="210px">
          <template #default="scope">
            <el-button type="success" @click="showItem(scope.row)">
              <template #icon>
                <i-ep-Search/>
              </template>
              查看明细
            </el-button>
            <el-button v-if="scope.row.status==='N'" type="danger" @click="stockAdjustFun(scope.row)">
              <svg-icon class="mr5" icon-class="adjustment"/>
              库存调整
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getGroupList"/>

    </el-dialog>

  </div>
</template>
<script lang="ts">
export default {
  name: "DrugInventoryCheckPreparation"
}
</script>

<script setup lang="ts">
import {
  addDrugInventoryCheckPreparation,
  delDrugInventoryCheckPreparation,
  getInventoryCheckListPreparation,
  updateDrugInventoryCheckPreparation,
  listDrugInventoryCheckPreparation,
  selectPageDrugInventoryCheckPreparation
} from "@/api/drug/drugInventoryCheckPreparation";

import {
  addDrugInventoryCheck, listDrugInventoryCheck, updateDrugInventoryCheck, selectGroupInventoryNo, stockAdjust
} from "@/api/drug/drugInventoryCheck";

import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";

const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData("clinic_or_visit", "charge_flag_dict",
  "drug_classification", "sys_yes_no", "position_type", "sys_user_sex", "confirm_flag", "spec_unit"))
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo


let solidFillFlag = false
const queryParamsRef = ref()
const drugInventoryCheckPreparationList = ref<any>([]);
const open = ref(false);
const showSearch = ref(true);
// 总条数
const total = ref<number>(0)
// 预盘点总条数
const totalPreparation = ref<any>(0)
const pageSize = ref<any>(50)
const title = ref("");
const groupInventoryList = ref<any>([])
// 是否最终保存
let saveTypeInfo = ref(false)
// 是否隐藏零库存
const isZeroInventory = ref(false)

const queryParams = ref<DrugInventoryCheckPreparationType>({
  pageNum: 1,
  pageSize: pageSize.value,
  orgId: userInfo.orgId,
  checkYearMonth: proxy.$parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
  inventoryNo: "",
  saveType: "",
  stockId: "",
  drugCode: "",
  drugClass: "",
  drugInfoId: "",
  storageId: proxy.$currentSelectDept,
  batchNo: "",
})

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  generateInventory();
}

/** 生成盘点单 */
function generateInventory() {
  solidFillFlag = false
  if (!queryParams.value.checkYearMonth) {
    return ElMessage.error("请先选择盘点日期后再生成。")
  }
  const param = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    drugCode: queryParams.value.drugCode,
    drugName: queryParams.value.drugInfoId,
    drugClass: queryParams.value.drugClass,
    itemNo: queryParams.value.itemNo,
    orgId: userInfo.orgId,
    storageId: proxy.$currentSelectDept,
    checkYearMonth: proxy.$parseTime(queryParams.value.checkYearMonth, '{y}-{m}-{d} {h}:{i}:{s}')
  }
  getInventoryCheckListPreparation(param).then((res: resType) => {
    totalPreparation.value = res.total
    if (res.rows.length > 0) {
      saveTypeInfo.value = false
      generateInventoryInit(res.rows)
    }
  })
}

/** 查询药品预盘点表 */
function getList() {
  if (!queryParams.value.orgId) {
    return ElMessage.error(proxy.$OrgIdIsEmpty)
  }
  selectPageDrugInventoryCheckPreparation(queryParams.value).then((res: any) => {
    totalPreparation.value = res.total
    generateInventoryInit(res.rows)
  })
}

function paginationClick() {
  const lastIndex = drugInventoryCheckPreparationList.value.length - 1;
  if (!drugInventoryCheckPreparationList.value[0].saveType
    || drugInventoryCheckPreparationList.value[0].saveType === '2'
    || !drugInventoryCheckPreparationList.value[lastIndex].saveType
    || drugInventoryCheckPreparationList.value[lastIndex].saveType === '2'
  ) {
    // 当前页为  实盘填充状态，自动调用暂存方法
    temporarySave()
  }
  queryParams.value.checkYearMonth = proxy.$parseTime(queryParams.value.checkYearMonth, '{y}-{m}-{d} {h}:{i}:{s}')
  queryParams.value.storageId = proxy.$currentSelectDept
  getList()
}


function generateInventoryInit(data: any) {
  drugInventoryCheckPreparationList.value = data
  drugInventoryCheckPreparationList.value.forEach((item: any) => {
    initDataOne(item)
  })
}


/**
 * 初始化计算每一条数据
 * @param item
 */
function initDataOne(item: any) {
  item.quantityMax = Math.floor(item.accountQuantity / item.packageNum)
  item.quantityMin = item.accountQuantity % item.packageNum
  item.profitQuantityMin = item.profitQuantity % item.packageNum
  // 盈亏数转化显示大单位
  if (item.profitQuantity < 0) {
    item.profitQuantityMax = 0 - Math.floor((Math.abs(item.profitQuantity / item.packageNum)))
  } else {
    item.profitQuantityMax = Math.floor(item.profitQuantity / item.packageNum)
  }
  item.quantityMinActual = item.actualQuantity % item.packageNum
  item.quantityMaxActual = Math.floor(item.actualQuantity / item.packageNum)
}

/**
 * 加载确认后的盘点记录明细
 * @param row
 */
function showItem(row: any) {
  listDrugInventoryCheck({inventoryNo: row.inventoryNo, orgId: userInfo.orgId}).then((res: resType) => {
    generateInventoryInit(res.data)
    saveTypeInfo.value = true
    totalPreparation.value = 0
    open.value = false
  })
}

/**
 * 调整库存
 */
function stockAdjustFun(row: any) {
  ElMessageBox.confirm('确认要进行库存调整吗',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    stockAdjust(row.inventoryNo, row.orgId).then(() => {
      drugInventoryCheckPreparationList.value = []
    })
  }).catch(() => {
  })
}

/**
 * 单行实盘数修改事件
 * @param row  行元数据
 * @param index  行号
 * @param type 事件类型
 */
function quantityActualBlur(item: any, _index: number, _type: string) {
  const quantityMinActual: number = item.quantityMinActual || 0
  const quantityMaxActual: number = item.quantityMaxActual || 0
  // 实盘数量（小包装）
  const actualNum = calculateNum(Number(quantityMaxActual), Number(quantityMinActual), Number(item.packageNum))
  item.actualQuantity = actualNum
  // 实盘额
  item.actualMoney = (actualNum * item.tradePriceMin).toFixed(2)
  // 实盘额销售
  item.actualMoneySales = (actualNum * item.retailPriceMin).toFixed(2)
  // 盈亏数 (小单位)
  const profitNum = actualNum - item.accountQuantity
  item.profitQuantity = profitNum
  // 盈亏数转化显示小单位
  item.profitQuantityMin = profitNum % item.packageNum
  // 盈亏数转化显示大单位
  if (profitNum < 0) {
    item.profitQuantityMax = 0 - Math.floor((Math.abs(profitNum / item.packageNum)))
  } else {
    item.profitQuantityMax = Math.floor(profitNum / item.packageNum)
  }
  // 盈亏额进价
  item.profitMoney = (profitNum * item.tradePriceMin).toFixed(2)
  // 盈亏额销售
  item.profitMoneySales = (profitNum * item.retailPriceMin).toFixed(2)
}

/** 提取盘点单 */
function extractInventory() {
  open.value = true
  title.value = "盘点单记录查询"
  getGroupList()
}

function getGroupList() {
  const param = {
    orgId: userInfo.orgId,
    storageId: proxy.$currentSelectDept,
  }
  selectGroupInventoryNo(param).then((res: resType) => {
    groupInventoryList.value = res.rows
    total.value = res.total || 0
  })
}

/** 删除盘点单 */
function deleteInventory() {
  if (drugInventoryCheckPreparationList.value.length <= 0) {
    return ElMessage.error("请先选择生成盘点单后，再操作。")
  }
  const inventoryNo = drugInventoryCheckPreparationList.value[0].inventoryNo
  if (inventoryNo) {
    ElMessageBox.confirm('是否确认删除药品预盘点表编号为"' + inventoryNo + '"的数据？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      delDrugInventoryCheckPreparation(drugInventoryCheckPreparationList.value[0].inventoryNo, userInfo.orgId).then(() => {
        drugInventoryCheckPreparationList.value = []
        ElMessage.success("删除成功");
      })
    })
  } else {
    drugInventoryCheckPreparationList.value = []
  }
}

/** 实盘填充 */
function solidFill() {
  if (drugInventoryCheckPreparationList.value.length <= 0) {
    return ElMessage.error("请先选择生成盘点单后，再操作。")
  }
  // if (drugInventoryCheckPreparationList.value[0].id) {
  //   return ElMessage.error("盘点数据已暂存或者保存，不能进行【实盘填充】。")
  // }
  if (solidFillFlag) {
    ElMessageBox.confirm('已经进行过实盘填充操作，如果确定修改，实盘数将会被重置，是否继续？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      solidFillOk()
    }).catch(() => {
    })
  } else {
    solidFillOk()
  }
}

/** 实盘填充确认数据组织 */
function solidFillOk() {
  listDrugInventoryCheckPreparation({inventoryNo: drugInventoryCheckPreparationList.value[0].inventoryNo}).then((res) => {
    let list: any = []
    res.data.forEach(item => {
      initDataOne(item)
      item.quantityMaxActual = item.quantityMax
      item.quantityMinActual = item.quantityMin
      const lastMinNum = calculateNum(item.quantityMaxActual || 0, item.quantityMinActual || 0, item.packageNum);
      const profitNum = item.accountQuantity - lastMinNum
      item.actualQuantity = lastMinNum
      item.profitQuantityMin = 0
      item.profitQuantityMax = 0
      item.profitQuantity = 0
      item.profitMoney = (item.tradePriceMin * profitNum).toFixed(2)
      item.profitMoneySales = (item.retailPriceMin * profitNum).toFixed(2)
      item.actualMoney = item.accountMoney
      item.actualMoneySales = item.accountMoneySales
      item.orgId = userInfo.orgId
      list.push(item)
    })
    const data = {
      drugInventoryCheckPreparationBoList: list,
      orgId: userInfo.orgId,
      saveType: "2"
    }
    updateDrugInventoryCheckPreparation(data).then(() => {
      ElMessage.success("实盘填充成功");
      queryParams.value.checkYearMonth = proxy.$parseTime(queryParams.value.checkYearMonth, '{y}-{m}-{d} {h}:{i}:{s}')
      queryParams.value.storageId = proxy.$currentSelectDept
      getList()
    })
  })
}

/**
 * 计算小库存数量
 * @param maxNum
 * @param minNum
 * @param packageNum
 */
function calculateNum(maxNum: number, minNum: number, packageNum: number) {
  return (maxNum * packageNum + minNum) as number;
}

/** 暂存 */
function temporarySave() {
  if (drugInventoryCheckPreparationList.value.length <= 0) {
    return ElMessage.error("请先选择生成盘点单后，再操作。")
  }
  // if (drugInventoryCheckPreparationList.value[0].saveType === null && !solidFillFlag) {
  //   return ElMessage.error("新生成的盘点数据需要先进行[实盘填充]后，才可以进行暂存操作。")
  // }
  const data = {
    checkYearMonth: proxy.$parseTime(queryParams.value.checkYearMonth, '{y}-{m}-{d} {h}:{i}:{s}'),
    drugInventoryCheckPreparationBoList: drugInventoryCheckPreparationList.value,
    orgId: userInfo.orgId,
    saveType: "4"
  }

  if (drugInventoryCheckPreparationList.value[0].id) {
    updateDrugInventoryCheckPreparation(data).then(() => {
      ElMessage.success(`第${queryParams.value.pageNum}页，暂存成功`);
      getList()
    }).finally(() => {
    });
  } else {

    addDrugInventoryCheckPreparation(data).then(() => {
      ElMessage.success(`第${queryParams.value.pageNum}页，暂存成功`);
      getList()
    }).finally(() => {
    });
  }
  // })
}

/** 保存 */
function save() {

  if (drugInventoryCheckPreparationList.value.length <= 0) {
    return ElMessage.error("请先选择生成盘点单后，再操作。")
  }
  if (drugInventoryCheckPreparationList.value[0].saveType === '0' && !solidFillFlag) {
    return ElMessage.error("新生成的盘点数据需要先进行【实盘填充】后，才可以进行暂存操作。")
  }
  const data = {
    checkYearMonth: proxy.$parseTime(queryParams.value.checkYearMonth, '{y}-{m}-{d} {h}:{i}:{s}'),
    drugInventoryCheckBoList: drugInventoryCheckPreparationList.value,
    orgId: userInfo.orgId,
    saveType: "1",
    inventoryNo: drugInventoryCheckPreparationList.value[0].inventoryNo,
    checkYearMonthEnd: proxy.$parseTime(drugInventoryCheckPreparationList.value[0].checkYearMonthEnd, '{y}-{m}-{d} {h}:{i}:{s}')
  }
  ElMessageBox.confirm('盘点数据未暂存，确认要直接保存吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    addDrugInventoryCheck(data).then(() => {
      ElMessage.success("保存成功");
      drugInventoryCheckPreparationList.value = []
    }).finally(() => {
    });
  })
}

/** 打印 */
function printInventory() {

}

/** 导出 */
function exportInventory() {
  proxy.$download('/drug/drugInventoryCheck/export', {
    inventoryNo: drugInventoryCheckPreparationList.value[0].inventoryNo,
    storageId: proxy.$currentSelectDept,
    orgId: userInfo.orgId,
    isZeroInventory: isZeroInventory.value,
  }, `药品盘点${drugInventoryCheckPreparationList.value[0].inventoryNo} - ${proxy.$parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")}.xlsx`)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('drug/drugInventoryCheckPreparation/export', {
    ...queryParams.value
  }, `drugInventoryCheckPreparation_${new Date().getTime()}.xlsx`)
}

function tableCellStyle({row, column, rowIndex, columnIndex}) {
  let rowBackground: any = {}
  if (columnIndex == 11 || columnIndex == 16 || columnIndex == 17) {
    if (row.quantityMax === row.quantityMaxActual && row.quantityMin === Number(row.quantityMinActual)) {
      rowBackground.background = "#33cc66 !important"
    } else if (row.profitQuantityMax < 0 || row.profitQuantityMin < 0) {
      rowBackground.background = "#ffcc66 !important"
    } else {
      rowBackground.background = "#ffcaca !important"
      rowBackground.color = "#000000 !important"
    }

  }
  return rowBackground
}

/**
 * 隐藏行
 */
const tableRowClassName = (row: any, _rowIndex: number) => {
  debugger
  if ((row.row.accountQuantity == null || row.row.accountQuantity == 0) && isZeroInventory.value) {
    return 'hidden-row'
  } else {
    return ''
  }
}
</script>

<style>
.dialog-mb .el-dialog__body {
  margin-bottom: 20px !important;
}

.el-table__body tr.hidden-row > td {
  display: none !important;
}
</style>
